package Thred;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author jiashaopeng
 * @create 2021-03-24
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //模拟一个抢车位的场景，假设一共有6个车，3个停车位
        Semaphore semaphore = new Semaphore(3,false);
        // 模拟6部车
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    // 代表一辆车，已经占用了该车位
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "\t 抢到车位");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName() + "\t 离开车位");
            } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
                },String.valueOf(i)).start();
        }
    }
}
